//
//  UITextView+Extension.swift
//  04-表情键盘
//
//  Created by Admin on 16/9/18.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

// MARK: - 扩展UITextView,处理插入表情,和将表情图片转换成表情文本
extension UITextView {
    
    /// 获取带表情图片的文本字符串
    func emoticonText() -> String {
        var strM = ""
        
        self.attributedText.enumerateAttributes(in: NSRange(location: 0, length: attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (dict, range, _) in
            // 判断是否是附件
            if let attachmet = dict["NSAttachment"] as? HMTextAttachment {
                let str = attachmet.chs!
                print(str)
                strM += str
            } else {
                // 不是附件,截取对应的文本
                let str = (attributedText.string as NSString).substring(with: range)
                strM += str
            }
        }
        
        return strM
    }
    
    /**
     插入表情到textView
     parameter emoticon: 表情模型
     */
    func insertEmoticon(emoticon: HMEmoticonModel) {
        
        // 插入emoji
        if let emoji = emoticon.emoji {
            insertText(emoji)
            return
        }
        
        // 插入表情图片,需要使用到属性文本
        if let pngPath = emoticon.fullPngPath {
//            // 附件,图片可以作为附件,附件可以添加到属性文本
//            let attachment = HMTextAttachment()
//            attachment.image = UIImage(contentsOfFile: pngPath)
//            attachment.chs = emoticon.chs
//            
//            // 获取文本的高度
//            let height = font?.lineHeight ?? 10
//            // 设置附件的大小
//            attachment.bounds = CGRect(x: 0, y: -4, width: height, height: height)
//            
//            // 创建带附件的属性文本,并且添加font属性
//            let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//            attrString.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
            let attrString = emoticon.toAttrString(font: font!)
            
            // 获取textView现有文本
            let attrStringM = NSMutableAttributedString(attributedString: attributedText)
            
            // 光标位置
            let oldSelectedRange = selectedRange
            
            // 替换属性文本到对应的位置
            attrStringM.replaceCharacters(in: oldSelectedRange, with: attrString)
            
            // 将属性文本设置给textView
            attributedText = attrStringM
            
            // 重新设置光标位置
            selectedRange = NSRange(location: oldSelectedRange.location + 1, length: 0)
            
            // 主动调用 textViewDidChange
            delegate?.textViewDidChange!(self)
            //
            // 主动发送 UITextViewTextDidChangeNotification 通知
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: self)
        }
    }
}
